package com.situ.mall.controller;

import com.situ.mall.pojo.Product;
import com.situ.mall.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/getProductListPage")
    public String selectById(Integer categoryId, Model model) {
        List<Product> list = productService.selectByCategotyId(categoryId);
        model.addAttribute("list", list);
        return "product_list";
    }

    @RequestMapping("/getProductDetailPage")
    public String getProductDetailPage(Integer productId, Model model) {
        Product product = (Product) redisTemplate.opsForValue().get("produt:" + productId);
        if (product == null) {
            System.out.println("product:" + productId + "在Redis缓存中没有查询数据库");
            product = productService.selectById(productId);
            if (product == null) {// 这个商品在Redis缓存和数据库里面都没有
                // product:123   new Product()
                // product:3444   new Product()
                // product:5656   new Product()
                redisTemplate.opsForValue().set("produt:" + productId, new Product(), 1, TimeUnit.MINUTES);
            } else {
                redisTemplate.opsForValue().set("produt:" + productId, product);
            }
        }
        model.addAttribute("product", product);
        return "product_detail";
    }


}
